package com.wuyou.controller;

import cn.hutool.json.JSONUtil;
import com.wuyou.domain.Result;
import com.wuyou.dto.UserDTO;
import com.wuyou.em.ResultEnum;
import com.wuyou.entity.User;
import com.wuyou.exception.LoginException;
import com.wuyou.util.JwtUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.client.RestClientTest;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/userLogin")
public class UserLoginController {


    @Autowired
    private JwtUtil jwtUtil;


    @GetMapping
    public String test(){
        return "111";
    }

    //用户单点登录
    @PostMapping
    @ApiOperation(value = "用户单点登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "nickname", value = "用户账号", required = true,
                    paramType = "path", dataTypeClass = String.class),
            @ApiImplicitParam(name = "password", value = "用户密码", required = true,
                    paramType = "path", dataTypeClass = String.class)
    })
    public Result userLogin(String nickname ,String password){
        //获取用户主题      工具类
        Subject subject = SecurityUtils.getSubject();
        //封装token
        UsernamePasswordToken token = new UsernamePasswordToken(nickname, password);
        //
        try {
            subject.login(token);
        }catch (UnknownAccountException e) {
            e.printStackTrace();
            return Result.R(ResultEnum.UNKNOWN_ACCOUNT);

        }catch (IncorrectCredentialsException e) {

            return Result.R(ResultEnum.PASSWORD_ERROR);
        }catch (LoginException e){
            return Result.R(ResultEnum.VERIFICATION_CODE_ERROR);
        }

        //登录后任意位置获取用户
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        //放入登录信息(账号,密码,id)
        UserDTO bto = UserDTO.builder().userId(user.getUserId()).userName(user.getUserName()).build();
        //将信息加密返回前端
        String tokenLogin = jwtUtil.createJwt(user.getUserId().toString(), JSONUtil.toJsonStr(bto), user.getIsHost().toString());


        return Result.OK().setData(tokenLogin);
    }

}
